package com.yue.se.encode;

import java.io.*;

/**
 * 功能描述: TODO <br/>
 * 创建时间: 2016/8/8<br/>
 *
 * @author QiuYang
 */
public class Char2Byte {
    public static void main(String[] args) {
        String file = "javase-summary/src/main/java/com/yue/se/encode/code.txt";
        String charset = "UTF-8";

        // 写入文件
        FileOutputStream outputStream = null;
        OutputStreamWriter streamWriter = null;
        try {
            outputStream = new FileOutputStream(file);
            streamWriter = new OutputStreamWriter(outputStream, charset);

            streamWriter.write("中国人");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (streamWriter != null) {
                    streamWriter.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        // 读取
        FileInputStream inputStream = null;
        InputStreamReader streamReader = null;
        StringBuffer buffer  = new StringBuffer();
        try {
            inputStream = new FileInputStream(file);
            streamReader = new InputStreamReader(inputStream, /*"GBK"*/charset);

            int count = 0;
            char[] buf = new char[64];

            while ((count = streamReader.read(buf)) != -1) {
                buffer.append(buf, 0, count);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != streamReader) {
                    streamReader.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println(buffer.toString());
    }
}
